package org.boge.sharpdoc.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.boge.sharpdoc.dao.DocumentDao;
import org.boge.sharpdoc.bean.DocGroup;
import org.boge.sharpdoc.bean.Document;
import org.boge.sharpdoc.config.Settings;
import org.boge.sharpdoc.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.List;

@Service
@Transactional
public class DocumentService {
    @Autowired
    private Settings settings;
    @Autowired
    private DocumentDao documentDao;

    public Document findDocById(Integer docid) {
        return documentDao.findById(docid);
    }

    public void uploadDocument(Document document) {
        String cmd = new File(settings.getDocumentDealDir(), "DocumentDeal.exe").getAbsolutePath() + " -r "
                + new File(settings.getDocsDir(), document.getStoredname())
                + " -f " + document.getStoredname() + " -s " + document.getSuffixicon().getSuffix();
        // 开启新线程进行文件的处理
        Thread thread = new Thread(() -> {
            try {
                // 调用外部程序，将文件处理
                Process process = Runtime.getRuntime().exec(cmd);
                // 线程阻塞，等待完成
                process.waitFor();
                // 处理文档的外部程序只有一个输出，即文档的页数
                // 获取进程的输出流，相对于当前进程，是输入流
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "GBK");
                BufferedReader br = new BufferedReader(isr);
                // 读取一行
                String line = br.readLine();
//                while ((line = br.readLine()) != null) {
//                    System.out.println("行:"+line);
//                    System.out.flush();
//                }
                // 关闭流
                isr.close();
                br.close();
                is.close();
                // 设置文档的页数
                document.setPages(Integer.parseInt(line));
                // 将文档的信息存储进数据库中
                documentDao.addItem(document);
                // 删除本地文件夹
                CommonUtil.deleteDir(new File(new File(settings.getDocsDir(), document.getStoredname()), "pdfs"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }

    public Integer getDocumentCount() {
        return documentDao.findCount();
    }

    public List<Document> getHotestDocs() {
        return documentDao.findHottestDocs();
    }

    public Integer updateHot(Integer docid) {
        return documentDao.updateHot(docid);
    }

    public List<Document> findByGroups(List<DocGroup> docGroups) {
        return documentDao.findByGroups(docGroups);
    }

    public PageInfo<Document> searchDocs(String keyword, Integer order, Integer index, Integer pageSize) {
        String sqlorder = "";
        //按热度排序
        if (order == 0)
            sqlorder += "hot desc,uploadtime desc";
        else
            sqlorder += "uploadtime desc,hot desc";
        return PageHelper.startPage(index, pageSize, sqlorder).doSelectPageInfo(() -> documentDao.findByKeyword(keyword));
    }

    public PageInfo<Document> searchDocs(List<DocGroup> groups, String keyword, Integer order, Integer index, Integer pageSize) {
        String sqlorder = "";
        //按热度排序
        if (order == 0)
            sqlorder += "hot desc,uploadtime desc";
        else
            sqlorder += "uploadtime desc,hot desc";
        return PageHelper.startPage(index, pageSize, sqlorder).doSelectPageInfo(() -> documentDao.findByGroupsAndKeyword(keyword, groups));
    }

    public PageInfo<Document> getAllDocumentsByStatusWithPage(String status, Integer index, Integer pageSize) {
        return PageHelper.startPage(index, pageSize, "uploadtime desc").doSelectPageInfo(() -> documentDao.findByStatus(status));
    }

    public Integer updateDownloadTimes(Integer docid) {
        return documentDao.updateDownloadTimes(docid);
    }

    public Integer changeStatus(Integer docid, String status) {
        return documentDao.updateStatus(docid, status);
    }

    public Integer updateAuditor(Integer docid, Integer adminid) {
        return documentDao.updateAuditor(docid, adminid);
    }
}